<?php
class Cart_CartController extends Ext_Controller_Action
{
	
	public function preDispatch()
	{
		parent::preDispatch();
		$this->_helper->layout->disableLayout();
	}
	
    public function showAction()
    {
		
    	if( $this->_hasParam('customer')) {
			$customerId = $this->_getParam('customer');
		} else {
			throw new Ext_Exception( 'El id de cliente es necesario' );
		}
		
    	if( $this->_hasParam('hash')) {
			$token = $this->_getParam('hash');
		} else {
			throw new Ext_Exception( 'No en mi codigo ;)' );
		}
		
		$client = new Zend_Rest_Client('http://application.dev:8001/CartWS/Cart/rest');

		try{
			$result = $client->getActiveOrder( $customerId )->get();
    	}catch( Exception $e) {
			throw new Ext_Exception($e);
		}

		$orderId = (int) $result->getActiveOrder->response;
		$this->view->orderId = $orderId; 

		try{
			$result = $client->getStatus($orderId)->get();
		}catch( Exception $e) {
			throw new Ext_Exception($e);
		}
		
		
	 	/*$result =  $client->getContactPhone( $orderId )->get();
		if( empty( $result->getConctactPhone->response )){

			$client->setContactPhone( $orderId, '01142349048' )->get();
			$result =  $client->getContactPhone( $orderId )->get();
		}
		$this->view->contactPhone = $result->getContactPhone->response;*/
		
		
		/*$result = $client->getOrderHistory($customerId)->get();
		if( empty( $result->getOrderHistory->resonse )){
			;
		} else {
			;
		}*/

		try{
			$result = $client->getOrderLines( $orderId )->get();
		}catch ( Exception $e ){
			throw new Ext_Exception($e);
		}
		
		echo Zend_Json::encode( $result->getOrderLines->response );
		exit;
		$this->view->lines = (array) $result->getOrderLines->response;
    }
    
    public function addlineAction()
    {
    	$this->_helper->layout->disableLayout();
    	if( $this->_hasParam('lineId')) {
			$lineId = $this->_getParam('lineId');
		} else {
			throw new Ext_Exception( 'El id de la linea es requerido' );
		}
    	
		if( $this->_hasParam('quantity')) {
			$quantity = $this->_getParam('quantity');
		} else {
			$quantity = 1;
		}
    	
		$client = new Zend_Rest_Client('http://application.dev:8001/CartWS/Cart/rest');
				
		try{
			$line = $client->getOrderLine( $lineId )->get()->getOrderLine;
			$data = (array) $line;
			$data['ordered_quantity'] = $quantity;
		}catch ( Exception $e ){
			throw new Ext_Exception( $e->getMessage() );
		}	

		try{
			$result = $client->addOrderLine( 
				$line->sales_order_id, 
				$data 
			)->get();
			echo Zend_Json::encode( array('error'=>0));
		}catch ( Exception $e ){
			echo Zend_Json::encode( array('error'=>0));
			echo $e->getMessage();
		}	
		exit;
   }
    

}